package com.example.graduatetest.view.model;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.ViewModel;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.baidu.geofence.GeoFenceClient;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.example.graduatetest.R;
import com.example.graduatetest.adapter.CardAdapter;
import com.example.graduatetest.bean.Card;
import com.example.graduatetest.bean.Classes;
import com.example.graduatetest.bean.User;
import com.example.graduatetest.callback.CardListCallBack;
import com.example.graduatetest.callback.OneClassCallBack;
import com.example.graduatetest.callback.StringCallBack;
import com.example.graduatetest.databinding.ActivitySendCardBinding;
import com.example.graduatetest.model.CardModel;
import com.example.graduatetest.utils.Constant;
import com.example.graduatetest.utils.TimeGet;

import java.util.ArrayList;
import java.util.List;

public class SendCardViewModel extends ViewModel {
    private int SUCCESS = 1,FAIL = 2;
    private Activity activity;
    private ActivitySendCardBinding binding;
    private MyLocationListener myListener = new MyLocationListener();
    private TextView location_text;
    private List<Card> cardList = new ArrayList<>();
    private String meter;
    private String minute;
    private String id;
    private String locationDescribe;
    private double lat,lon;
    private int flag=FAIL;
    private User user;
    private Classes ownclasses;
    private android.os.Handler handler = new Handler();

    public void init(Activity activity, ActivitySendCardBinding binding,Classes classes){
        this.activity = activity;
        this.binding = binding;
        this.ownclasses = classes;
        user = Constant.checkStudentOrTeacher(activity);
        toolbarInit();
        getCardList();
    }
   //方法重载
    public void init(Activity activity, ActivitySendCardBinding binding){
        this.activity = activity;
        this.binding = binding;
        this.ownclasses = null;
        user = Constant.checkStudentOrTeacher(activity);
        toolbarInit();
        getCardList();
    }

    private void locationInit(){
        Log.e("haha", "kkk");
        LocationClient mLocationClient = new LocationClient(activity.getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //获取地址选项
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedLocationDescribe(true);
        option.setCoorType("BD09LL");
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        mLocationClient.setLocOption(option);

        mLocationClient.start();
    }

    //初始toolbar
    private void toolbarInit(){
        Toolbar toolbar = binding.toolbar5;
        toolbar.setTitle("发布打卡");
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activity.onBackPressed();
            }
        });

    }

    //初始化recyclerView
    private void recyclerInit(){
        LinearLayoutManager layoutManager = new LinearLayoutManager(activity);
        binding.ryCardItem.setLayoutManager(layoutManager);
        CardAdapter cardAdapter = new CardAdapter(cardList,activity);
        binding.ryCardItem.setAdapter(cardAdapter);
    }

    //获取服务器Card List
    private void getCardList(){
        CardModel.getCardList(user.getNumber(), new CardListCallBack() {
            @Override
            public void onSuccess(List<Card> list) {
                cardList = list;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        recyclerInit();
                    }
                });
                Log.e("haha", "获取card列表成功");
            }

            @Override
            public void onFailed() {
                Log.e("haha", "获取card列表失败");
            }
        });
    }

    //发布打开按钮点击事件
    public void sendCardToShow(){
        //自定义登录对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        final AlertDialog dialog = builder.create();
        View dialogView = View.inflate(activity, R.layout.show_send_card, null);
        dialog.setView(dialogView);
        dialog.show();

        final ImageView cancelImage = (ImageView)dialogView.findViewById(R.id.cancel_action);
        final LinearLayout locationLinear = (LinearLayout)dialogView.findViewById(R.id.get_location_linear);
        location_text = (TextView)dialogView.findViewById(R.id.tv_location_text);
        final EditText meter_ed = (EditText)dialogView.findViewById(R.id.ed_meter);
        final EditText min_ed = (EditText)dialogView.findViewById(R.id.ed_min);
        final EditText number_ed = (EditText)dialogView.findViewById(R.id.ed_number);
        final Button bt_submit = (Button)dialogView.findViewById(R.id.bt_submit);

        //判断是否传入classes对象
        if(ownclasses != null){
            number_ed.setText(ownclasses.getId());
            Log.e("haa",ownclasses.getId());
        }

        cancelImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        locationLinear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                locationInit();
            }
        });
        bt_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                meter=meter_ed.getText().toString();
                minute=min_ed.getText().toString();
                id=number_ed.getText().toString();
                if(!TextUtils.isEmpty(meter) && !TextUtils.isEmpty(minute) && !TextUtils.isEmpty(id) && !location_text.getText().equals("***")){
                    CardModel.getOneClass(id, new OneClassCallBack() {
                        @Override
                        public void onSuccess(final Classes classes) {
                                flag = SUCCESS;
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        setCard(dialog,id,classes.getNumber());
                                    }
                                });
                                //dialog.dismiss();
                        }

                        @Override
                        public void onFailed() {
                            flag = FAIL;
                            //Toast.makeText(activity, "网络错误", Toast.LENGTH_SHORT).show();
                        }
                    });

                }else{
                    Toast.makeText(activity, "输入信息为空或错误", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    //设置card属性
    private void setCard(AlertDialog dialog,String id, int allNumber){
        //判断是否成功
        if(flag == SUCCESS){
            dialog.dismiss();
            Card card = new Card();
            card.setTime(TimeGet.getDate());
            card.setStatus("正在考勤");
            card.setSet_meter(Integer.parseInt(meter));
            card.setClass_number(id);
            card.setStay_s(Integer.parseInt(minute)*60);
            card.setId(TimeGet.getUId());
            card.setCode(TimeGet.getRandomString(6));
            card.setAsk_number(0);
            card.setIn_number(0);
            card.setOut_number(0);
            card.setDelay_number(0);
            card.setTeacher_code(user.getNumber());
            card.setAll_number(allNumber);
            card.setAddress(locationDescribe);
            card.setLat(lat);
            card.setLon(lon);


            cardList.add(card);
            if(binding.ryCardItem.getAdapter() != null){
                binding.ryCardItem.getAdapter().notifyDataSetChanged();
            }

            updateOnlineCards(card);

        }else{
            Toast.makeText(activity, "网络错误", Toast.LENGTH_SHORT).show();
        }

    }

    //上传到云数据库
    private void updateOnlineCards(Card card){
        CardModel.addOneCard(card, new StringCallBack() {
            @Override
            public void onSuccess(String result) {
                if(!result.equals("fail")){
                    String id = result;
                    Log.e("haha", id);
                }

            }

            @Override
            public void onFailed() {
              Log.e("haha", "上传card信息失败");
            }
        });
    }

    public class MyLocationListener implements BDLocationListener{
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            locationDescribe = bdLocation.getLocationDescribe();//获取位置描述信息
            location_text.setText(locationDescribe);
            lat = bdLocation.getLatitude();
            Log.e("haha", lat+"");
            lon = bdLocation.getLongitude();
            Log.e("haha", lon+"");
        }
    }
}
